<?php
require_once APPPATH.'third_party/kdt/lib/YZGetTokenClient.php';
require_once APPPATH.'third_party/kdt/lib/YZTokenClient.php';
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/6/23
 * Time: 11:30
 */
class Kdt_api_model extends Base_Model
{
    private $_appid;
    private $_appsecret;
    private $_client;
    private $_client_id;
    private $_client_secret;
    private $_access_token;
    private $_refresh_token;
    private $_redis;
    private $_expires_in;
    private $_refresh_expires_in;

    public function __construct()
    {
        parent::__construct();

        $this->config->load('kdt');
        $this->_appid = $this->config->item('appid');
        $this->_appsecret = $this->config->item('appsecret');
        $this->_client_id = $this->config->item('clientid');
        $this->_client_secret = $this->config->item('clientSecret');
        $this->_refresh_expires_in = 2160000;
        $this->load->model('redis_model');
        $this->_redis = $this->redis_model->getRedisInstance();
    }

    public function checkToken()
    {
        $token = $this->_redis->get('kdt_access_token');
        //超时重新获取
        if ($token===false){
            $rtoken = $this->_redis->get('kdt_refresh_token');
            //重新授权,跳转页面
            if ($rtoken===false){
                $this->getToken();
            }
            //刷新token
            else{
                $this->_refresh_token=$rtoken;
                $this->refreshToken();
            }
        }else{$this->_access_token=$token;}
    }

    public function getAccessToken()
    {
        return $this->_access_token;
    }

    public function getToken()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $redirectUrl = 'http://admin.nldou.com/kdtauthapi/authcallback';
        $this->_client->getCode($redirectUrl);
    }

    public function authcallback()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $keys = array();
        $redirectUrl = 'http://admin.nldou.com/kdtauthapi/authcallback';
        $type = 'oauth';
        $keys['code'] = $_GET['code'];
        $keys['redirect_uri'] = $redirectUrl;

        $res = $this->_client->getToken( $type , $keys );
        $this->_access_token=$res['access_token'];
        $this->_refresh_token=$res['refresh_token'];
        $this->_expires_in=(int)$res['expires_in'];
        $this->saveToken();
    }

    public function refreshToken()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $type = 'refresh_token';
        $keys = array();
        $keys['refresh_token'] = $this->_refresh_token;

        $res = $this->_client->getToken( $type , $keys );
        $this->_access_token=$res['access_token'];
        $this->_refresh_token=$res['refresh_token'];
        $this->_expires_in=(int)$res['expires_in'];
        $this->saveToken();
    }

    public function saveToken()
    {
        //保存access_token,过期时间（7天-1小时）
        $this->_redis->set('kdt_access_token',$this->_access_token);
        $this->_redis->expire('kdt_access_token',$this->_expires_in-3600);
        //保存refresh_token,过期时间（25天）
        $this->_redis->set('kdt_refresh_token',$this->_refresh_token);
        $this->_redis->expire('kdt_refresh_token',$this->_refresh_expires_in);
    }

    public function getTradesSold($start,$end,$pageno,$pagesize=50)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.trades.sold.get';
        $methodVersion = '3.0.0';

//        $now = time();
//        $start = date('Y-m-d H:i:s',$now-30*24*3600);
//        $start = '2018-01-01 00:00:00';
//        $end = date('Y-m-d H:i:s',$now);
        $params = array(
            'start_created' => $start,
            'end_created'=> $end,
            'page_no'=>$pageno,
            'page_size'=>$pagesize,
            'use_has_next'=>true
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response'])) return $res['response'];
        else return false;
    }

    public function getSalesmanTrades($mobile,$start,$stop)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.trades.get';
        $methodVersion = '3.0.0';
        $files = array();

        $pageno = 1;
        $data = array();
        //循环页码
        while (true){
            $params = array(
                'start_time' => $start,
                'end_time'=> $stop,
                'page_size' => 40,
                'page_no'=>$pageno,
                'mobile'=>$mobile,
                'fans_type'=>1,
                'fans_id'=>0
            );
            $res = $this->_client->post($method, $methodVersion, $params, $files);
            if (!isset($res['response']['trades'])) {echo "kdt api error".PHP_EOL;exit();}
            if (empty($res['response']['trades'])) break;
            $data=array_merge($data,$res['response']['trades']);
            $pageno++;
        }

        return $data;
    }

    public function getGoodsInfo()
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        //在售商品
        $method = 'youzan.items.onsale.get';
        $methodVersion = '3.0.0';

        $params = array(
            'order_by'=>"created_time:des"
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        $data = array();
        if (!isset($res['error_response'])){
            $data['onsale']['count']=(int)$res['response']['count'];//在售商品数量
            echo 'onsale count '.$res['response']['count'].PHP_EOL;
            if (isset($res['response']['items'])){
                foreach ($res['response']['items'] as $t){
                    $data['onsale']['goods'][]=array("num_iid"=>$t['item_id'],"title"=>$t['title']);
                    echo 'onsale '.$t['item_id'].' '.$t['title'].PHP_EOL;
                }
            }
        }else{
            $data['onsale']['count']=0;
            echo 'onsale api error'.PHP_EOL;
        }
        echo '----------------------------'.PHP_EOL;
        //仓库中商品
        $method = 'youzan.items.inventory.get';
        $methodVersion = '3.0.0';

        $params = array(
            'order_by'=>"created_time:des"
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (!isset($res['error_response'])){
            $data['unsale']['count']=(int)$res['response']['count'];//仓库商品数量
            echo 'unsale count '.$res['response']['count'].PHP_EOL;
            if (isset($res['response']['items'])){
                foreach ($res['response']['items'] as $t){
                    $data['unsale']['goods'][]=array("num_iid"=>$t['item_id'],"title"=>$t['title']);
                    echo 'unsale '.$t['item_id'].' '.$t['title'].PHP_EOL;
                }
            }
        }else{
            $data['unsale']['count']=0;
            echo 'unsale api error'.PHP_EOL;
        }
    }

    public function getSalesmanAccount($mobile)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.account.get';
        $methodVersion = '3.0.0';

        $params = array(
            'mobile' => $mobile,
            'fans_id'=>0,
            'fans_type' => 1
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['seller'])) return $res['response'];
        else return false;
    }

    public function getSalesmanList($pageno)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.accounts.get';
        $methodVersion = '3.0.0';

        $params = array(
            'page_size' => 40,
            'page_no' => $pageno
        );

        $files = array();
        $res = $this->_client->post($method, $methodVersion, $params, $files);

        if (isset($res['response']['accounts'])) return $res['response']['accounts'];
        else return false;
    }

    public function getSalesmanCustomers($pagesize,$pageno,$mobile)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.customers.get';
        $methodVersion = '3.0.0';

        $params = array(
            'page_size'=>$pagesize,
            'page_no'=>$pageno,
            'mobile'=>$mobile,
            'fans_type'=>1,
            'fans_id'=>0
        );

        $files = array();

        return $this->_client->post($method, $methodVersion, $params, $files);
    }

//    public function getCouponList()
//    {
//        $this->checkToken();
//        $this->_client = new YZTokenClient($this->_access_token);
//
//        $method = 'youzan.ump.coupons.unfinished.search';
//        $methodVersion = '3.0.0';
//
//        $params = array();
//
//        $files = array();
//
//        $res = $this->_client->post($method, $methodVersion, $params, $files);
//        if (isset($res['response']['coupons'])) return $res['response']['coupons'];
//        else return false;
//    }

    public function getCouponList()
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.ump.coupon.search';
        $methodVersion = '3.0.0';

        $params = array(
            'status'=>'ON',
            'page_size'=>50,
            'page_no'=>1,
            'group_type'=>'PROMOCARD'

        );

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['groups'])) return $res['response']['groups'];
        else return false;
    }

    public function getGoodsOnSale($pageno)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.items.onsale.get';
        $methodVersion = '3.0.0';

        $params = array(
            'page_no'=>$pageno,
            'page_size'=>20
        );

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['items'])) return $res['response']['items'];
        else return false;
    }
}